package net.zoneland.knowledge.utils;

import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

/**
 *
 */
public class HttpClientUtils {

    /**
     * 参数以json形式传送
     * @return
     * @throws IOException
     */
    public static String doPost(String url, String json, Map<String, String> headerMap) throws IOException {

        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();

        // 创建httppost对象
        HttpPost httpPost = new HttpPost(url);

        // 给httppost对象设置json格式的参数
        StringEntity httpEntity = new StringEntity(json, "utf-8");

        // 设置请求格式
        httpPost.setHeader("Content-type", "application/json");
        Iterator<Map.Entry<String, String>> iterator = headerMap.entrySet().iterator();
        Map.Entry<String, String> elem = null;
        while (iterator.hasNext()) {
            elem = iterator.next();
            httpPost.addHeader(elem.getKey(), elem.getValue());
        }
        // 传参
        httpPost.setEntity(httpEntity);
        try {
            CloseableHttpResponse closeableHttpResponse = closeableHttpClient.execute(httpPost);
            return EntityUtils.toString(closeableHttpResponse.getEntity(), "utf-8");
        } catch (IOException e) {
            throw e;
        } finally {
            closeableHttpClient.close();
        }
    }


    /**
     *  TODO get请求
     * @param url
     * @param headerMap
     * @return
     * @throws IOException
     */
    public static String doGet(final String url, final Map<String, String> headerMap) throws IOException {
        final CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        // 创建httppost对象
        final HttpGet httpGet = new HttpGet(url);
        // 设置请求格式
        final Iterator<Map.Entry<String, String>> iterator = headerMap.entrySet().iterator();
        while (iterator.hasNext()) {
            final Map.Entry<String, String> elem = iterator.next();
            httpGet.addHeader(elem.getKey(), elem.getValue());
        }
        try {
            final CloseableHttpResponse closeableHttpResponse = closeableHttpClient.execute(httpGet);
            return EntityUtils.toString(closeableHttpResponse.getEntity(), "utf-8");
        } catch (IOException e) {
            throw e;
        } finally {
            closeableHttpClient.close();
        }
    }
}
